<!-- 苗木搜索--求购列表 -->
<template>
  <div class="search-container">
    <div class="header-wrapper">
      <div class="header-search">
        <div @click="onClickLeft" class="icon"><van-icon class="back" name="arrow-left" /></div>
        <van-search
          v-model="params.keyword"
          show-action
          shape="round"
          placeholder="请输入搜索关键词"
          @search="onSearch"
        >
          <template #action>
            <div @click="onSearch">搜索</div>
          </template>
        </van-search>
      </div>

      <div class="sort-wrapper">
        <van-dropdown-menu ref="mnenuRef">
          <van-dropdown-item v-if="qualityOptions.length > 0" :title="qualityName" ref="sortRef">
            <van-cell
              :class="[item.selected ? 'selected' : '']"
              center
              :title="item.dictValue"
              v-for="(item, index) in qualityOptions"
              :key="index"
              @click="handleSelectSortQuality(item, index)"
            />
          </van-dropdown-item>
          <van-dropdown-item :title="cityName">
            <van-tree-select
              v-model:active-id="activeId"
              v-model:main-active-index="activeIndex"
              :items="allCity"
              @click-item="selectCity"
            />
          </van-dropdown-item>
        </van-dropdown-menu>
        <div class="sort-item" @click="showMore = true">
          <span>更多筛选</span><van-icon name="filter-o" />
        </div>
      </div>
    </div>

    <div class="list-wrapper van-hairline--top">
      <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        :immediate-check="true"
        @load="onLoad"
      >
        <div class="item" v-for="item in categoryList" :key="item.id" @click="viewDetail(item)">
          <div class="left"><img :src="item.imgUrl" /></div>
          <div class="right">
            <div class="head">
              <div class="title">
                <span class="name">{{ item.title }}</span>
              </div>
              <div class="address">{{ item.receiveProvince + item.receiveCity }}</div>
            </div>
            <div class="attribute-wrapper">
              <template v-for="(attr, index) in item.attributeDocuments" :key="index"
                >{{ attr.attributeName }}:{{ attr.minValue }}-{{ attr.maxValue
                }}{{ attr.unit + '&nbsp&nbsp' }}
              </template>
            </div>
            <div class="pullNum">
              <span>求购数量:{{ item.pullNum }}&nbsp;&nbsp;求购期限:{{ item.pullTime }}天</span>
            </div>
            <div class="pullNum">
              <span>期望货源:{{ item.deliverProvince + item.deliverCity }}</span>
            </div>
            <div class="auth-wrapper">
              <div class="auth van-hairline--surround" v-if="item.authType == 1">
                <van-image :src="auth" width="12" height="12" />实名认证
              </div>
              <div class="auth van-hairline--surround" v-if="item.companyAuthType == 1">
                <van-image :src="auth" width="12" height="12" />企业认证
              </div>
            </div>
          </div>
        </div>
      </van-list>
    </div>

    <van-popup v-model:show="showMore" position="right" :style="{ width: '80%', height: '100%' }">
      <div class="more-wrapper">
        <div class="top">
          <div class="title">规格（厘米）</div>
          <div class="item" v-for="item in allProductCategory.attributes" :key="item.id">
            <span>{{ item.attributeName }}</span>
            <van-field class="field1" v-model="item.minValue" placeholder="最低" />-
            <van-field class="field2" v-model="item.maxValue" placeholder="最高" />
          </div>
          <div class="title" style="margin-bottom: 12px">类型</div>
          <div class="planAttributes">
            <div
              class="plan-item"
              v-for="(item, index) in allProductCategory.plantAttributes"
              :key="item.id"
              @click="toggleSelection(item, index)"
              :class="[item.selected ? 'selected' : '']"
            >
              {{ item.plantAttributeName }}
            </div>
          </div>
        </div>
        <div class="bottom van-hairline--top">
          <van-button round color="#32BC05" plain @click="reset">重置</van-button>
          <van-button round color="#32BC05" @click="confirm">确定</van-button>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script lang="ts" setup>
import bridge from '@/utils/bridge.js'
import { pullProductQuery, dictData, getProductCategoryAttributesV3, getAll } from '@/api'
import auth from '../../assets/auth.png'
const activeId = ref(-1)
const activeIndex = ref(-1)
const router = useRouter()
const route = useRoute()
// 排序信息
const qualityOptions = ref([])
// 所有植物分类
const allProductCategory = ref({})
// 所有城市
const allCity = ref([])
// 查询结果
const categoryList = ref([])
const loading = ref(false)
const finished = ref(false)
const showMore = ref(false)
const sortRef = ref(null)
const mnenuRef = ref(null)
const qualityName = ref('品质')
const cityName = ref('地区')
// 搜索条件
const params = ref({
  pageSize: 10,
  pageNum: 1,
  keyword: ''
})

onMounted(async () => {
  bridge.setNavigationBarVisible({
    value: '0'
  })
  params.value.keyword = route.query.keyword
  getList()
  getAllProductCategory()
  getAllCity()
  qualityOptions.value = await getDictData('es_product_quality')
})

// 返回上一页
const onClickLeft = () => {
  bridge.closeWebView()
}

// 获取排序字典
const getDictData = async (type: string) => {
  let { code, data } = await dictData(type)
  if (code === 200) {
    data.map((item) => {
      item.selected = false
    })
    return data
  }
}

// 获取所有城市
const getAllCity = async () => {
  let { code, data } = await getAll()
  if (code === 200) {
    processCityData(data)
  }
}

// 处理城市数据
const processCityData = (data) => {
  data.map((item) => {
    item.text = item.label
    if (item.children) {
      item.children.map((child) => {
        child.text = child.label
      })
    }
  })
  allCity.value = data
}

// 获取所有属性类型
const getAllProductCategory = async () => {
  let { code, data } = await getProductCategoryAttributesV3()
  if (code === 200) {
    allProductCategory.value = data[0]
    allProductCategory.value.plantAttributes.map((item) => {
      item.selected = false
    })
  }
}

// 选择类型
const toggleSelection = (item, index) => {
  allProductCategory.value.plantAttributes.map((plant, idx) => {
    if (idx === index) {
      item.selected = !item.selected
    } else {
      plant.selected = false
    }
  })
}

// 选择排序
const handleSelectSortQuality = (item, index) => {
  qualityOptions.value.map((o, i) => {
    if (i === index) {
      o.selected = true
    } else {
      o.selected = false
    }
  })
  mnenuRef.value.close()
  params.value.quality = item.dictLabel
  qualityName.value = item.dictValue
  onSearch()
}

// 选择地区
const selectCity = (item) => {
  mnenuRef.value.close()
  params.value.cityCode = item.code
  params.value.provinceCode = allCity.value[activeIndex.value].code
  cityName.value = item.label
  onSearch()
}

// 重置
const reset = () => {
  getAllProductCategory()
}

// 确定
const confirm = () => {
  params.value.attributes = allProductCategory.value.attributes
  params.value.plantAttributeId = allProductCategory.value.plantAttributes.find(
    (item) => item.selected
  )?.plantAttributeId
  showMore.value = false
  onSearch()
}

const onLoad = () => {
  params.value.pageNum++
  getList()
}

// 获取列表数据
const getList = async () => {
  loading.value = true
  try {
    let { code, rows, total } = await pullProductQuery(params.value)
    if (code === 200) {
      rows.map((item) => {
        item.imgUrl = item.ossUrls.split(',')[0]
      })
      categoryList.value.push(...rows)
      if (categoryList.value.length >= total) {
        finished.value = true
      }
    }
  } finally {
    loading.value = false
  }
}

// 搜索
const onSearch = async () => {
  params.value.pageNum = 1
  categoryList.value = []
  finished.value = false
  getList()
}

const viewDetail = (item: any) => {
  router.push({
    path: '/purchaseDetail',
    query: {
      pullProductId: item.id,
      type: '1'
    }
  })
}
</script>

<style lang="scss" scoped>
.search-container {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100vh;
  background-color: #fff;
  padding-top: constant(safe-area-inset-top); /* 标准 */
  padding-top: env(safe-area-inset-top); /* iOS 11.0+ */
  .header-wrapper {
    padding: 0 12px;

    .header-search {
      display: flex;
      align-items: center;
      justify-content: space-between;

      .icon {
        width: 20px;
        height: 30px;
        text-align: left;
        line-height: 30px;
        .van-icon {
          font-size: 17px;
        }
      }

      :deep(.van-search) {
        flex: 1;

        .van-cell {
          font-size: 13px;
        }

        .van-search__action {
          padding: 0 0 0 10px;
          font-size: 13px;
        }
      }
    }

    .sort-wrapper {
      display: flex;
      align-items: center;
      justify-content: space-between;

      :deep(.van-dropdown-menu) {
        flex: 0 0 75%;

        .van-dropdown-menu__bar {
          box-shadow: none;
          background: #fff;
        }

        .van-dropdown-menu__title {
          color: #222;
          font-size: 13px;
          line-height: 44px;
        }

        .van-cell {
          font-size: 13px;
          text-align: center;
          &.selected {
            color: #32bc05;
          }
        }
      }

      .sort-item {
        flex: 0 0 25%;
        color: #222;
        font-size: 13px;
        line-height: 44px;
        text-align: center;
      }
    }
  }

  .list-wrapper {
    flex: 1;
    overflow-y: auto;

    .van-list {
      padding: 0 12px;

      .item {
        padding: 10px 0;
        display: flex;
        align-items: top;
        justify-content: space-between;
        gap: 8px;

        .left {
          flex: 0 0 130px;
          width: 130px;
          height: 97px;
          object-fit: cover;
          border-radius: 4px;
          overflow: hidden;

          img {
            display: block;
            width: 100%;
            height: 100%;
            object-fit: cover;
          }
        }

        .right {
          flex: 1;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          overflow: hidden;

          .head {
            display: flex;
            align-items: center;
            justify-content: space-between;

            .title {
              display: flex;
              align-items: center;
              gap: 4px;

              .name {
                color: #222;
                font-size: 14px;
                font-weight: 400;
                line-height: 21px;
              }
            }

            .address {
              font-size: 10px;
              color: #999;
            }
          }

          .attribute-wrapper {
            font-size: 11px;
            color: #222;
            line-height: 15px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }

          .pullNum {
            display: flex;
            align-items: center;
            justify-content: space-between;
            gap: 8px;
            font-size: 11px;
            color: #222;
            line-height: 15px;
          }

          .company {
            font-size: 11px;
            color: #999;
            line-height: 15px;
          }

          .auth-wrapper {
            display: flex;
            align-items: center;

            .auth {
              padding: 0 6px;
              margin-right: 6px;
              display: flex;
              align-items: center;
              font-size: 11px;
              color: #c8933b;
              line-height: 18px;

              &::after {
                border-radius: 15px;
                border-color: #c8933b;
              }
            }
          }
        }
      }
    }
  }

  :deep(.van-sidebar-item) {
    font-size: 14px;
    color: #666;

    &.van-sidebar-item--select {
      color: #32bc05;
      font-weight: 400;
    }
  }

  :deep(.van-tree-select__item) {
    font-weight: 400;
    font-size: 14px;
    color: #666;

    &.van-tree-select__item--active {
      color: #32bc05;
    }
  }

  .more-wrapper {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;

    .top {
      padding: 0 16px 14px 16px;
      overflow-y: auto;

      .title {
        margin-top: 28px;
        font-size: 14px;
        color: #222;
        line-height: 20px;
      }

      .item {
        margin: 12px 0;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 12px;
        color: #666;
        font-weight: 400;

        span {
          flex: 1;
        }

        :deep(.van-field) {
          padding: 0;
          width: 80px;
          height: 28px;
          line-height: 28px;
          text-align: center;
          background: #f5f5f5;
          border: 1px solid #ddd;
          border-radius: 2px;

          &.field1 {
            margin-right: 5px;
          }

          &.field2 {
            margin-left: 5px;
          }

          .van-field__control {
            text-align: center;
            font-size: 12px;
            color: #666;
          }
        }
      }

      .planAttributes {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        gap: 10px;

        .plan-item {
          height: 36px;
          line-height: 36px;
          border-radius: 18px;
          // padding: 0 26px;
          font-size: 12px;
          color: #666;
          background: #f5f5f5;
          flex: 0 0 30%;
          text-align: center;

          &.selected {
            background: rgba(50, 188, 5, 0.1);
            color: #32bc05;
          }
        }
      }
    }

    .bottom {
      padding: 10px 16px;
      flex: 1;
      display: flex;
      align-items: center;
      gap: 12px;
      justify-content: space-between;

      :deep(.van-button) {
        height: 40px;
        flex: 1;
      }
    }
  }
}
</style>
